package com.qxzn.module.home.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.adapter.NumericWheelAdapter;
import com.contrarywind.listener.OnItemSelectedListener;
import com.contrarywind.view.WheelView;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.UserRemindBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.interfaces.MyInterface;
import com.qxzn.app.page.model.HomeModel;
import com.qxzn.app.page.view.CustomItemView;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.DateUtil;
import com.qxzn.app.util.MathUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.home.R;
import com.qxzn.module.home.R2;

import butterknife.BindView;
import butterknife.OnClick;

public class EditRemindActivity extends BaseActivity implements MyInterface.AddRemindListener, MyInterface.UpdateRemindListener, MyInterface.DelRemindListener {
    @BindView(R2.id.wv_time_hour)
    WheelView wvTimeHour;
    @BindView(R2.id.wv_time_min)
    WheelView wvTimeMin;
    @BindView(R2.id.civ_remind_repeat)
    CustomItemView civRemindRepeat;
    @BindView(R2.id.civ_remind_content)
    CustomItemView civRemindContent;
    @BindView(R2.id.tv_delete)
    TextView tvDelete;
    private NumericWheelAdapter hourAdapter;
    private String hour;
    private NumericWheelAdapter minAdapter;
    private String min;
    private int repeatType = 3;
    private String repeatValue;
    private HomeModel homeModel;
    private boolean remindContentEmpty = true;
    private String id;
    private boolean isEdit;
    private String username;

    @Override
    protected int initLayout() {
        return R.layout.activity_edit_remind;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText("编辑定时提醒");
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("完成");
        tv_right.setTextColor(Color.parseColor("#2A8CFF"));
        tv_right.setOnClickListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        homeModel = new HomeModel(this);
        homeModel.setAddRemindListener(this);
        UserRemindBean bean = (UserRemindBean) getIntent().getSerializableExtra("bean");
        if (bean != null) {
            isEdit = true;
            username = bean.getUsername();
            String time = bean.getMedicinetime();
            if (time != null) {
                String[] times = time.split(":");
                if (times != null && times.length > 1) {
                    hour = times[0];
                    min = times[1];
                }
            }
            repeatType = bean.getType();
            repeatValue = bean.getTypevalue();
            setRepeatItem();
            if (!TextUtils.isEmpty(bean.getTitle())) {
                remindContentEmpty = false;
                civRemindContent.setRightText(bean.getTitle());
            }
            tvDelete.setVisibility(View.VISIBLE);
            id = bean.getId();
            homeModel.setUpdateRemindListener(this);
            homeModel.setDelRemindListener(this);
        } else {
            username = getIntent().getStringExtra(Constant.PutExtraKey.USERNAME);
        }
        initTimeViewData();
    }

    private void initTimeViewData() {
        hourAdapter = new NumericWheelAdapter(0, 23);
        wvTimeHour.setAdapter(hourAdapter);
        int a;
        if (TextUtils.isEmpty(hour)) {
            a = MathUtil.parseInt(DateUtil.formMillisToStr(System.currentTimeMillis(), "HH"));
        } else {
            a = MathUtil.parseInt(hour);
        }
        wvTimeHour.setCurrentItem(a);
        wvTimeHour.setCyclic(false);
        wvTimeHour.setDividerType(WheelView.DividerType.WRAP);
        wvTimeHour.setDividerColor(Color.parseColor("#4B97F4"));
        wvTimeHour.setTextColorCenter(Color.parseColor("#4B97F4"));
        wvTimeHour.setTextColorOut(Color.parseColor("#AFAFAF"));
        wvTimeHour.setTextSize(20);
        wvTimeHour.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                hour = getValue(hourAdapter, index);
            }
        });
        hour = getValue(hourAdapter, a);

        minAdapter = new NumericWheelAdapter(0, 59);
        wvTimeMin.setAdapter(minAdapter);
        int b;
        if (TextUtils.isEmpty(min)) {
            b = MathUtil.parseInt(DateUtil.formMillisToStr(System.currentTimeMillis(), "mm"));
        } else {
            b = MathUtil.parseInt(min);
        }
        wvTimeMin.setCurrentItem(b);
        wvTimeMin.setCyclic(false);
        wvTimeMin.setDividerType(WheelView.DividerType.WRAP);
        wvTimeMin.setDividerColor(Color.parseColor("#4B97F4"));
        wvTimeMin.setTextColorCenter(Color.parseColor("#4B97F4"));
        wvTimeMin.setTextColorOut(Color.parseColor("#AFAFAF"));
        wvTimeMin.setTextSize(20);
        wvTimeMin.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                min = getValue(minAdapter, index);
            }
        });
        min = getValue(minAdapter, b);
    }

    private String getValue(NumericWheelAdapter adapter, int index) {
        String value = adapter.getItem(index) + "";
        if (value.length() == 1) {
            value = "0" + value;
        }
        return value;
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_right) {
            if (repeatType == -1) {
                AppUtil.showToast(this, "请选择重复类型");
                return;
            }
            JSONObject params = new JSONObject();
            params.put("username", username);
            params.put("title", remindContentEmpty ? "" : civRemindContent.getRightText());
            params.put("type", repeatType);
            params.put("typevalue", repeatValue);
            params.put("medicinetime", hour + ":" + min);
            params.put("state", "1");
            params.put("mold", "1");
            params.put("device_id", SharePreferenceUtil.getDeviceId(EditRemindActivity.this));
            params.put("medicinedate", DateUtil.parseStrToMillis(DateUtil.formMillisToStr(System.currentTimeMillis(), DateUtil.yearToDatePattern1) + hour + ":" + min, DateUtil.yearToDatePattern1 + DateUtil.hourToMinPattern));
            if (isEdit) {
                if (TextUtils.isEmpty(id)) {
                    AppUtil.showToast(this, "数据有误，请稍后再试！");
                    return;
                }
                params.put("id", id);
                homeModel.updateRemind(params);
            } else {
                params.put("device_id", SharePreferenceUtil.getDeviceId(this));
                homeModel.addRemind(params);
            }
        }
    }

    @OnClick({R2.id.civ_remind_repeat, R2.id.civ_remind_content, R2.id.tv_delete})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.civ_remind_repeat) {
            startActivityForResult(new Intent(this, RemindRepeatActivity.class).putExtra(Constant.PutExtraKey.REPEAT_TYPE, repeatType).putExtra(Constant.PutExtraKey.REPEAT_VALUE, repeatValue), 1);
        } else if (i == R.id.civ_remind_content) {
            startActivityForResult(new Intent(this, InputRemindContentActivity.class).putExtra(Constant.PutExtraKey.CONTENT, remindContentEmpty ? "" : civRemindContent.getRightText()), 2);
        } else if (i == R.id.tv_delete) {
            if (TextUtils.isEmpty(id)) {
                AppUtil.showToast(this, "数据有误，请稍后再试！");
                return;
            }
            showDialog("删除提示", "是否确认删除该任务提醒？", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    JSONObject params = new JSONObject();
                    params.put("id", id);
                    params.put("device_id", SharePreferenceUtil.getDeviceId(EditRemindActivity.this));
                    homeModel.delRemind(params);
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                if (data == null) {
                    return;
                }
                repeatType = data.getIntExtra(Constant.PutExtraKey.REPEAT_TYPE, -1);
                if (repeatType == -1) {
                    return;
                }
                repeatValue = data.getStringExtra(Constant.PutExtraKey.REPEAT_VALUE);
                setRepeatItem();
            } else if (requestCode == 2) {
                if (data != null) {
                    if (TextUtils.isEmpty(data.getStringExtra(Constant.PutExtraKey.CONTENT))) {
                        remindContentEmpty = true;
                        civRemindContent.setRightText("未添加");
                    } else {
                        remindContentEmpty = false;
                        civRemindContent.setRightText(data.getStringExtra(Constant.PutExtraKey.CONTENT));
                    }
                }
            }
        }
    }

    private void setRepeatItem() {
        if (repeatType == 0) {
            civRemindRepeat.setRightText("每天");
        } else if (repeatType == 1) {
            civRemindRepeat.setRightText(DateUtil.getWeekStrByWeekNum(repeatValue, "周"));
        } else if (repeatType == 2) {
            civRemindRepeat.setRightText("每隔" + repeatValue);
        } else if (repeatType == 3) {
            civRemindRepeat.setRightText("只响一次");
        }
    }

    @Override
    public void onAddRemindSuccess(BaseBean baseBean) {
        showCallback(baseBean, "添加");
    }

    @Override
    public void onAddRemindFailure() {

    }

    @Override
    public void onDelRemindSuccess(BaseBean baseBean) {
        showCallback(baseBean, "删除");
    }

    @Override
    public void onDelRemindFailure() {

    }

    @Override
    public void onUpdateRemindSuccess(BaseBean baseBean) {
        showCallback(baseBean, "更新");
    }

    @Override
    public void onUpdateRemindFailure() {

    }

    private void showCallback(BaseBean baseBean, String option) {
        if (baseBean != null && baseBean.getCode() == 200) {
            if (!TextUtils.isEmpty(baseBean.getMsg())) {
                AppUtil.showToast(this, baseBean.getMsg());
            } else {
                AppUtil.showToast(this, option + "提醒成功");
            }
            setResult(RESULT_OK);
            finish();
        } else {
            if (baseBean != null && !TextUtils.isEmpty(baseBean.getMsg())) {
                AppUtil.showToast(this, baseBean.getMsg());
            } else {
                AppUtil.showToast(this, option + "提醒失败");
            }
        }
    }

}
